package cn.com.elite;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Element;


public class IsPayInterface extends HttpServlet{
	private static final Log log=LogFactory.getLog(IsPayInterface.class);
	private static String[] TimeOutCode={"BX","C0","CX","DV","GR","HN","09","68","98"};
	
	private String getPaymentCancel(String OrderNo,String new_OrderNo,DataSource dataSource1){
		String ORDER_NUMBER="";
		String RESPONSE_CODE="";
		String RESPONSE_DESC="";
		String PAYMENT_ID="";
		String TRANS_DATE="";
		String TRANS_TIME="";
		String ERR_MSG="";
		String ERR_CODE="";	
		String BANK_CODE="";
		String ACCOUNT_TYPE="";
		String BANK_ACCOUNT="";
		String returnString="success";
		String RealOrderNo="";
		List OrderNo_list=ISPayServlet.ebean.chaxun_sql("select * from IsPayOrderNo where IVROrderNo='"+OrderNo+"' and flag=1",dataSource1);
		if(OrderNo_list!=null&&OrderNo_list.size()>0){
			Map OrderNo_map=(Map)OrderNo_list.get(0);
			RealOrderNo=(String)OrderNo_map.get("RealOrderNo");
			log.debug("getPaymentCancel_RealOrderNo:"+RealOrderNo);
		}
		try{
			int flag=1;
			String cancel_xml="<?xml version='1.0' encoding='UTF-8'?><BODY><PAYMENT_ID>"+new_OrderNo+"</PAYMENT_ID><MERCHANT_ID>"+ISPayServlet.MERCHANT_ID+"</MERCHANT_ID><ORG_PAYMENT_ID>"+RealOrderNo+"</ORG_PAYMENT_ID></BODY>";
			ISPayServlet.PorcessLog(cancel_xml,OrderNo,"调用反交易接口前","cancel_01",100,"",dataSource1);	
			String cancel_result="";
			try{
				cancel_result=ISPayServlet.ISPayConnection(ISPayServlet.PaymentCancel_url,ISPayServlet.indentity,ISPayServlet.authPasswd,cancel_xml,"indentity","300","xmlfile");
			}catch(Exception e){
				ISPayServlet.PorcessLog(cancel_result,OrderNo,"调用反交易接口后","cancel_02",2,"",dataSource1);	
				log.error(Util.getERRO(e));
			}		
			if(cancel_result==null||cancel_result.equals("")){
				ISPayServlet.PorcessLog(cancel_result,OrderNo,"调用反交易接口后","cancel_02",3,"",dataSource1);	
			}
			log.info("cancel_result:"+cancel_result);
			Element root1=ISPayServlet.ElementRoot(cancel_result);
			ORDER_NUMBER=ISPayServlet.getElementValue(root1.getChild("ORDER_NUMBER"));
			RESPONSE_CODE=ISPayServlet.getElementValue(root1.getChild("RESPONSE_CODE"));
			RESPONSE_DESC=ISPayServlet.getElementValue(root1.getChild("RESPONSE_DESC"));
			TRANS_DATE=ISPayServlet.getElementValue(root1.getChild("TRANS_DATE"));
			TRANS_TIME=ISPayServlet.getElementValue(root1.getChild("TRANS_TIME"));
			ERR_MSG=ISPayServlet.getElementValue(root1.getChild("ERR_MSG"));
			ERR_CODE=ISPayServlet.getElementValue(root1.getChild("ERR_CODE"));
			PAYMENT_ID=OrderNo;
			if(RESPONSE_CODE.equals("00")){
				flag=0;
				ISPayServlet.PorcessLog(cancel_result,OrderNo,"调用反交易接口后","cancel_02",1,"",dataSource1);	
			}else{
				ISPayServlet.PorcessLog(cancel_result,OrderNo,"调用反交易接口后","cancel_02",0,"",dataSource1);	
			}
			String ISIvrPay_result=ISPayServlet.ebean.ISIvrPay(ORDER_NUMBER, RESPONSE_CODE, RESPONSE_DESC, BANK_CODE, ACCOUNT_TYPE, PAYMENT_ID, TRANS_DATE, TRANS_TIME, ERR_MSG, ERR_CODE,BANK_ACCOUNT,flag,dataSource1,OrderNo,RealOrderNo);
		    log.info("ISIvrPay_result:"+ISIvrPay_result);
			String sql="update IsPayOrderNo set flag="+flag+" where RealOrderNo='"+RealOrderNo+"' and IVROrderNo='"+OrderNo+"'";
			log.info("getPaymentCancel_sql:"+sql);
			int UpdateSqlresult=ISPayServlet.ebean.update_sql(sql,dataSource1);
			log.info("getPaymentCancel_UpdateSqlresult:"+UpdateSqlresult);
		}catch(Exception e){
			returnString="wrong";
			log.error("getPaymentCancel(String OrderNo):"+Util.getERRO(e));
		}
		return returnString;
	}
    public static String inputStreamToString(InputStream is,String encoding) throws IOException{
    	byte[] b=new byte[1024];
    	String res="";
    	if(is==null){
    		return "";
    	}
    	int bytesRead=0;
    	while(true){
    		bytesRead=is.read(b,0,1024);
    		if(bytesRead==-1){
    			return res;
    		}
    		res+=new String(b,0,bytesRead,encoding);
    	}
    }
    public static void main(String[] args){

    }
	private String getTongBu(String realtionID,DataSource dataSource1){
		String returnString="success";
		try{
			int flag=0;
			String TxXml=ISPayThread.getTxXml(realtionID,dataSource1,"01");
			TxXml="<?xml version='1.0' encoding='GBK'?><TXS>"+TxXml+"</TXS>";
			
//			InputStream in=IsPayInterface.class.getClassLoader().getResourceAsStream("1234.xml"); 
//	        String TxXml=inputStreamToString(in,"GBK");
			String returnxml=ISPayThread.getReturnXml(TxXml,"01");
			if(returnxml==null||returnxml.equals("")){
				ISPayServlet.PorcessLog(returnxml,realtionID,"调用同步接口后","01tongbu_02",3,"",dataSource1);
			}
			ISPayThread.parserXml(returnxml,dataSource1,"01",realtionID);
		}catch(Exception e){
			returnString="wrong";
			log.error("getTongBu(String realtionID):"+Util.getERRO(e));
		}
		return returnString;
	}
	public static String getPaymentQuery(String OrderNo,DataSource dataSource1){
		String ORDER_NUMBER="";
		String RESPONSE_CODE="";
		String RESPONSE_DESC="";
		String BANK_CODE="";
		String ACCOUNT_TYPE="";
		String PAYMENT_ID="";
		String TRANS_DATE="";
		String TRANS_TIME="";
		String ERR_MSG="";
		String ERR_CODE="";	
		String BANK_ACCOUNT="";
		String RealOrderNo="";
		int flag=2;
		List OrderNo_list=ISPayServlet.ebean.chaxun_sql("select * from IsPayOrderNo where IVROrderNo='"+OrderNo+"' and flag=2",dataSource1);
		if(OrderNo_list!=null&&OrderNo_list.size()>0){
			Map OrderNo_map=(Map)OrderNo_list.get(0);
			RealOrderNo=(String)OrderNo_map.get("RealOrderNo");
			log.debug("getPaymentQuery_RealOrderNo:"+RealOrderNo);
		}	
		try{
			String query_xml="<?xml version='1.0' encoding='UTF-8'?><BODY><MERCHANT_ID>888119948140055</MERCHANT_ID><PAYMENT_ID>"+RealOrderNo+"</PAYMENT_ID></BODY>";
			ISPayServlet.PorcessLog(query_xml,"","调用查询接口前","query_01",100,"",dataSource1);
			String query_result="";
			try{
				query_result=ISPayServlet.ISPayConnection(ISPayServlet.PaymentQuery_url,ISPayServlet.indentity,ISPayServlet.authPasswd,query_xml,"indentity","300","xmlfile");
			}catch(Exception e){
				ISPayServlet.PorcessLog(query_result,"","调用查询接口后","query_02",2,"",dataSource1);
				log.error(Util.getERRO(e));
			}
			if(query_result==null||query_result.equals("")){
				ISPayServlet.PorcessLog(query_result,OrderNo,"调用查询接口后","query_02",3,"",dataSource1);
			}
			log.info("query_result:"+query_result);
			Element root1=ISPayServlet.ElementRoot(query_result);
			ORDER_NUMBER=ISPayServlet.getElementValue(root1.getChild("ORDER_NUMBER"));
			RESPONSE_CODE=ISPayServlet.getElementValue(root1.getChild("RESPONSE_CODE"));
			RESPONSE_DESC=ISPayServlet.getElementValue(root1.getChild("RESPONSE_DESC"));
			BANK_CODE=ISPayServlet.getElementValue(root1.getChild("BANK_CODE"));
			ACCOUNT_TYPE=ISPayServlet.getElementValue(root1.getChild("ACCOUNT_TYPE"));
			PAYMENT_ID=ISPayServlet.getElementValue(root1.getChild("PAYMENT_ID"));
			TRANS_DATE=ISPayServlet.getElementValue(root1.getChild("TRANS_DATE"));
			TRANS_TIME=ISPayServlet.getElementValue(root1.getChild("TRANS_TIME"));
			ERR_MSG=ISPayServlet.getElementValue(root1.getChild("ERR_MSG"));
			ERR_CODE=ISPayServlet.getElementValue(root1.getChild("ERR_CODE"));
			BANK_ACCOUNT=ISPayServlet.getElementValue(root1.getChild("BANK_ACCOUNT"));
			if(RESPONSE_CODE.equals("00")){
				flag=1;
				ISPayServlet.PorcessLog(query_result,OrderNo,"调用查询接口后","query_02",1,"",dataSource1);
			}else{
				flag=0;
				for(int i=0;i<TimeOutCode.length;i++){
					if(RESPONSE_CODE.equals(TimeOutCode[i])){
						flag=2;
						ISPayServlet.PorcessLog(query_result,OrderNo,"调用查询接口后","query_02",2,"",dataSource1);
					}
				}
			}
			if(flag==0){
				ISPayServlet.PorcessLog(query_result,OrderNo,"调用查询接口后","query_02",0,"",dataSource1);
			}
			String ISIvrPay_result=ISPayServlet.ebean.ISIvrPay(ORDER_NUMBER, RESPONSE_CODE, RESPONSE_DESC, BANK_CODE, ACCOUNT_TYPE, PAYMENT_ID, TRANS_DATE, TRANS_TIME, ERR_MSG, ERR_CODE,BANK_ACCOUNT,flag,dataSource1,OrderNo,RealOrderNo);
			log.info("ISIvrPay_result:"+ISIvrPay_result);
			String sql="update IsPayOrderNo set flag="+flag+" where RealOrderNo='"+RealOrderNo+"' and IVROrderNo='"+OrderNo+"'";
			log.info("getPaymentQuery_sql:"+sql);
			int UpdateSqlresult=ISPayServlet.ebean.update_sql(sql,dataSource1);
			log.info("getPaymentQuery_UpdateSqlresult:"+UpdateSqlresult);
		}catch(Exception e){
			log.error("getPaymentQuery(String OrderNo):"+Util.getERRO(e));
		}
		return flag+"";
	}
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
		log.info("－－－－－－－－－－－－－－－－－－－IsPayInterface（202）－－－－－－－－－－－－－－－－－－");
		String returnString="";
		String type=request.getParameter("type");
		log.info("type:"+type);
		String OrderNo=request.getParameter("OrderNo");
		log.info("OrderNo:"+OrderNo);	
		String new_OrderNo=request.getParameter("new_OrderNo");
		log.info("new_OrderNo:"+new_OrderNo);
		String realtionID=request.getParameter("realtionID");
		log.info("realtionID:"+realtionID);
		String ProjectID=request.getParameter("ProjectID");
		log.info("ProjectID:"+ProjectID);
		DataSource dataSource1=(DataSource)ISPayServlet.wac.getBean(ProjectID);
		try{
			String param="type:"+type+"-"+"OrderNo:"+OrderNo+"-"+"new_OrderNo:"+new_OrderNo+"-"+"realtionID:"+realtionID+"-"+"ProjectID:"+ProjectID;
			if(param.length()>1000){
				param=param.substring(0,1000);
			}
			ISPayServlet.ebean.ISIvrPay_log(OrderNo,"接受到POST请求",param,"post_01",100,realtionID,dataSource1);
		}catch(Exception e){
			log.error(Util.getERRO(e));
		}
		
		try{
			if(type.equals("PaymentQuery")){
				returnString=getPaymentQuery(OrderNo,dataSource1);
				log.info("getPaymentQuery_returnString:"+returnString);
			}else if(type.equals("PaymentCancel")){
				returnString=getPaymentCancel(OrderNo,new_OrderNo,dataSource1);
				log.info("getPaymentCancel_returnString:"+returnString);
			}else if(type.equals("TongBu")){
				returnString=getTongBu(realtionID,dataSource1);
			}
		}catch(Exception e){
			
		}
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=utf-8;");
	    PrintWriter out=response.getWriter();
	    log.info("returnString:"+returnString);
	    out.print(returnString);
	}
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
		this.doPost(request, response);
	}

}